package example.servlet;

import com.alibaba.fastjson.JSONArray;
import example.pojo.SysRole;
import example.pojo.SysUser;
import example.service.RoleService;
import example.service.RoleServiceImpl;
import example.service.UserService;
import example.service.UserServiceImpl;
import example.util.Page;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/user")
@MultipartConfig(maxFileSize = 1024 * 1024 * 1)
public class UserServlet extends HttpServlet {


    private UserService userService = new UserServiceImpl();
    private RoleService roleService = new RoleServiceImpl();

    /**
     * 接收初始化参数
     */
    private String uploadPath;
    private PrintWriter out;
    //初始化参数

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        //获取全局初始化参数
        uploadPath = this.getServletContext().getInitParameter("uploadPath");
        System.out.println("全局初始化参数: uploadPath=" + uploadPath);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String opr = req.getParameter("opr");
        if (opr.equals("login")) {
            SysUser user = userService.login(req.getParameter("account"), req.getParameter("password"));
            if (user != null) {
                req.getSession().setAttribute("user", user);
                req.getRequestDispatcher("/WEB-INF/jsp/frame.jsp").forward(req, resp);
            } else {
                System.out.println("账号或密码有误");
                req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
            }
        } else if (opr.equals("list")) {
            //获取参数
            int pageIndex = Integer.parseInt(req.getParameter("pageIndex"));
            String queryRealName = req.getParameter("queryRealName");
            String queryRoleIdStr = req.getParameter("queryRoleId");
            //设置分页参数
            Page<SysUser> userPage = new Page<>();
            //设置总数据量
            userPage.setTotalPage(userService.count(queryRealName, queryRoleIdStr == null || queryRoleIdStr.equals("") ? null : Integer.parseInt(queryRoleIdStr)));
            //设置总页数
            userPage.setTotalPageSize();
            //设置当前页码
            userPage.setPageIndex(pageIndex);
            //获取当前页数据
            userPage.setList(userService.pageSelectUser(userPage.getPageIndex(), userPage.getPageSize(), queryRealName, queryRoleIdStr == null || queryRoleIdStr.equals("") ? null : Integer.parseInt(queryRoleIdStr)));
            //数据回显
            req.setAttribute("queryRealName", queryRealName);
            req.setAttribute("queryRoleId", queryRoleIdStr);
            List<SysRole> roleList = roleService.roleList();
            req.setAttribute("roleList", roleList);
            req.setAttribute("userList", userPage.getList());

            req.setAttribute("totalPageCount", userPage.getTotalPageSize());
            req.setAttribute("totalCount", userPage.getTotalPage());
            req.setAttribute("currentPageNo", userPage.getPageIndex());


            //获取角色数据
            req.getRequestDispatcher("/WEB-INF/jsp/sysUser/list.jsp").forward(req, resp);
        } else if (opr.equals("toAdd")) {
            //查询所有角色
            List<SysRole> roleList = roleService.roleList();
            req.setAttribute("roleList", roleList);
            req.getRequestDispatcher("/WEB-INF/jsp/sysUser/add.jsp").forward(req, resp);
        } else if (opr.equals("toUpdate")) {
            int uid = Integer.parseInt(req.getParameter("uid"));
            //查询所有角色
            List<SysRole> roleList = roleService.roleList();
            req.setAttribute("roleList", roleList);
            SysUser user = userService.getUserByIdOrAccount(uid, null);
            req.setAttribute("sysUser", user);
            req.getRequestDispatcher("/WEB-INF/jsp/sysUser/update.jsp").forward(req, resp);
        } else if (opr.equals("update")) {
            update(req, resp);
        } else if (opr.equals("userExist")) {
            switch (userService.accountExist(req.getParameter("account"))) {
                case 1:
                    out.println(1);
                    break;
                case 0:
                    out.println(0);
                    break;
                default:
                    out.println(-1);
                    break;
            }
        } else if (opr.equals("add")) {
            add(req, resp);
        } else if (opr.equals("det")) {
            int uid = Integer.parseInt(req.getParameter("uid"));
            String account = req.getParameter("account");
            SysUser user = userService.getUserByIdOrAccount(uid, account);
            if (user == null) {
                out.println("nodata");
            } else {
                String json = JSONArray.toJSONString(user);
                out.println(json);
            }
        } else if (opr.equals("del")) {
            int id = Integer.parseInt(req.getParameter("id"));
            if (userService.del(id) > 0) {
                out.println("true");
            } else {
                out.println("false");
            }
        } else if (opr.equals("checkOldPwd")) {
            checkOldPwd(req, resp);
        } else if (opr.equals("toUpdatePwd")) {
            req.getRequestDispatcher("/WEB-INF/jsp/sysUser/updatePassword.jsp").forward(req, resp);
        } else if (opr.equals("savePassword")) {
            savePassword(req, resp);
        }
    }

    private void savePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession().getAttribute("user") == null) {
            System.out.println("用户信息丢失，请重新登录试试吧？");
        }
        int id = ((SysUser) req.getSession().getAttribute("user")).getId();
        String newPassword = req.getParameter("newPassword");
        if (userService.updatePwd(id, newPassword) > 0) {
            System.out.println("密码修改成功");
            req.getSession().removeAttribute("user");
            req.getSession().invalidate();
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
        } else {
            System.out.println("密码修改失败");
            req.getRequestDispatcher("/WEB-INF/jsp/frame.jsp").forward(req, resp);
        }
    }

    private void checkOldPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        out = resp.getWriter();
        if (req.getSession().getAttribute("user") == null) {
            out.println("sessionerror");
        }
        int id = ((SysUser) req.getSession().getAttribute("user")).getId();
        String oldPassword = req.getParameter("oldPassword");
        if (oldPassword == null || oldPassword.equals("")) {
            out.println("error");
        }
        if (userService.checkOldPwd(id, oldPassword) > 0) {
            out.println("true");
        } else {
            out.println("false");
        }
    }


    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) {
            SysUser user = new SysUser();
            String account = req.getParameter("account");
            String realName = req.getParameter("realName");
            String password = req.getParameter("password");
            int sex = Integer.parseInt(req.getParameter("sex"));
            String birthday = req.getParameter("birthday");
            String phone = req.getParameter("phone");
            String address = req.getParameter("address");
            int roleId = Integer.parseInt(req.getParameter("roleId"));
            //获取文件
            Part idPicPart = req.getPart("idPic");
            Part workPicPart = req.getPart("workPic");
            //获取文件名
            String idPicFileName = extractFileName(idPicPart);
            String workPicFileName = extractFileName(workPicPart);
            //将文件写入
            idPicPart.write("E:\\S3\\ssm\\ch04\\src\\main\\webapp\\statics\\upload" + File.separator + idPicFileName);
            workPicPart.write("E:\\S3\\ssm\\ch04\\src\\main\\webapp\\statics\\upload" + File.separator + workPicFileName);
            System.out.println("身份照上传成功：" + idPicFileName);
            System.out.println("工作照上传成功：" + workPicFileName);
            user.setAccount(account);
            user.setRealName(realName);
            user.setPassword(password);
            user.setSex(sex);
            user.setBirthday(birthday);
            user.setPhone(phone);
            user.setAddress(address);
            user.setRoleId(roleId);
            user.setIdPic(uploadPath + File.separator + idPicFileName);
            user.setWorkPic(uploadPath + File.separator + workPicFileName);
            int count = userService.add(user);
            if (count > 0) {
                System.out.println("用户添加成功");
                req.getRequestDispatcher("user?opr=list&pageIndex=1").forward(req, resp);
            } else {
                System.out.println("用户添加失败");
                req.getRequestDispatcher("/WEB-INF/jsp/sysUser/list.jsp").forward(req, resp);
            }
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        int id = Integer.parseInt(req.getParameter("id"));
        String account = req.getParameter("account");
        SysUser userId = userService.getUserByIdOrAccount(id, account);
        String realName = req.getParameter("realName");
        String sexStr = req.getParameter("sex");
        String birthdayStr = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String roleId = req.getParameter("roleId");
        SysUser user = new SysUser(userId.getId(), account, realName, null, Integer.parseInt(sexStr), birthdayStr, phone, address, Integer.parseInt(roleId), 1, null, null);
        int count = userService.upd(user);
        if (count > 0) {
            System.out.println("修改成功");
            req.getRequestDispatcher("user?opr=list&pageIndex=1").forward(req, resp);
        } else {
            System.out.println("修改失败");
            req.getRequestDispatcher("user?opr=list&pageIndex=1").forward(req, resp);
        }
    }

    /**
     * 获取上传 的文件名
     */
    private String extractFileName(Part part) {
        String fileName = "";
        String contentDisp = part.getHeader("content-disposition");
        //将获取到的参数用   ；  分割
        String[] items = contentDisp.split(";");
        for (String s : items) {
            //获取以filename为前缀开始字符串
            if (s.trim().startsWith("filename")) {
                System.out.println(s + "========================================");
                //获取分割后的字符串
                return fileName = s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }


}
